import axios from 'axios'

// 配置axios实例
const api = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  },
})

// 获取用户信息
export const getUserInfo = async () => {
  try {
    const response = await api.get('/user/info')
    return response.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
    throw error
  }
}

// 用户登出
export const logout = async () => {
  try {
    await api.post('/user/logout')
  } catch (error) {
    console.error('登出失败:', error)
    throw error
  }
}

// 添加请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 处理token过期
          localStorage.removeItem('token')
          window.location.href = '/login'
          break
        case 403:
          // 处理权限不足
          break
        default:
          break
      }
    }
    return Promise.reject(error)
  }
)

export default api
